package com.yunpuvip.sachet.core.tag.tagfactory;

import com.yunpuvip.sachet.core.tag.TagName;
import org.apache.poi.ss.formula.functions.T;
import org.beetl.core.Tag;
import org.beetl.core.TagFactory;
import org.beetl.ext.spring.SpringBeanTagFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName BeetlTagFactoryManager
 * @Description TODO
 * @Autor wushaohong
 * @Date 2019/3/11
 * @Version 1.0
 */
@Component
public class BeetlTagFactoryManager implements ApplicationContextAware {

    private ApplicationContext applicationContext=null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;

    }



    @Bean(name = "tagFactorys")
    public Map<String, TagFactory> tagFactorys() {
        Map<String, TagFactory> tags = new HashMap<>();
        Map<String, Tag> beans = applicationContext.getBeansOfType(Tag.class);
        for(String name:beans.keySet()){
            //读取标签名
            TagName tagAnno = beans.get(name).getClass().getAnnotation(TagName.class);
            if(null==tagAnno){
                continue;
            }
            String  tagName= tagAnno != null ? tagAnno.value() : name;
            tags.put(tagName,getTagFactory(name));
        }
        return tags;
    }

    /**
     * 定义获得tag工厂
     * @param name
     * @return
     */
    public SpringBeanTagFactory getTagFactory(String name){
        SpringBeanTagFactory springBeanTagFactory = new SpringBeanTagFactory();
        springBeanTagFactory.setName(name);
        springBeanTagFactory.setApplicationContext(applicationContext);
        return springBeanTagFactory;
    }


}
